import qs from 'querystring';
// import np from 'nprogress';

import Http from '../lib/request';
import auth from '../util/auth';
import CONSTANT from '../constant/common';
// const { Loading } = require('element-ui');

// const env = process.env.NODE_ENV;
// mock
// const url = 'https://easy-mock.com/mock/5ad4c2a8bd35a15df646a1cf';
// development
// const url = 'http://116.196.71.57:8080';
const url = CONSTANT.REQUEST_URL; // 'http://wechat.zhaochunqi.com';
// const Authorization = auth.getToken();// 获取token

// get
const getData = (data, api) => {
  const qstring = qs.stringify(data);
  return Http.get(`${url}${api}?${qstring}`, {
    headers: {
      Authorization: auth.getToken(),
    },
  })
    .then((res) => {
      if (res.status !== 200) {
        throw new Error(data.message);
      }
      return res.data || {};
    });
};

// post
const postData = (data, api) =>
  Http.post(`${url}${api}`, data, {
    headers: {
      Authorization: auth.getToken(),
    },
  })
    .then((res) => {
      if (res.status !== 200) {
        return res || {};
      }
      return res.data || {};
    });

// post json
const postFormData = (data, api) =>
  Http.post(`${url}${api}`, qs.stringify(data), {
    headers: {
      Authorization: auth.getToken(),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  })
    .then((res) => {
      if (res.status !== 200) {
        throw new Error(res.message);
      }
      return res.data || {};
    });

// put
const putData = (data, api) => {
  Http.put(`${url}${api}`, data, {
    headers: {
      Authorization: auth.getToken(),
    },
  })
    .then((res) => {
      if (res.status !== 200) {
        throw new Error(res.message);
      }
      return res.data || {};
    });
};

const getBlobData = (data, api) => {
  const qstring = qs.stringify(data);
  return Http.get(`${url}${api}?${qstring}`, {
    headers: {
      Authorization: auth.getToken(),
    },
    responseType: 'blob',
  });
};

export default {
  getData,
  postData,
  postFormData,
  putData,
  getBlobData,
};
